var logger = require('./config/logger');

process.on('uncaughtException', function (err) {
  logger.error(err.stack);
  process.exit(1);
});

/**
 * Module dependencies.
 */

var express = require('express');
var expressValidator = require('express-validator');
var favicon = require('serve-favicon');
var http = require('http');
//var https = require('https');
var path = require('path');
var ejs = require('ejs');
var passport = require('passport');
var bodyParser = require('body-parser');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var CONFIG = require('./config/config').Config;
var fs = require('fs-extra');
var compression = require('compression');

var Common = require('./util/common');

var multipart = require('connect-multiparty');
var multipartMiddleware = multipart({uploadDir: __dirname + '/uploads'});

var app = express();

var engine = require('ejs-locals');
app.engine('.html', engine);

// all environments
app.set('port', process.env.PORT || CONFIG.port);

app.set('views', __dirname + '/views');
app.set('view engine', 'html');

//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(express.logger('dev'));

// body parsing middleware - above methodOverride()
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use(multipartMiddleware);

app.use(expressValidator());
app.use(express.cookieParser(CONFIG.sessionSecret));
app.use(express.methodOverride());

app.use(compression()); //use compression

var oneDaySeconds = 86400000;

app.use(function (req, res, next) {
  if (req.url.match(/^\/(css|icons|about|downloads|images|signUpImg|assets|js|oldzy|avatars|pictures|backgrounds)\/.+/)) {
    res.setHeader('Cache-Control', 'public, max-age=' + oneDaySeconds);
  }
  next();
});

app.use(express.static(path.join(__dirname, 'public')));

app.use(express.session());

require('./config/passport')(passport);
// !!!!Sequence important. Need to call express.session before passport.session
app.use(passport.initialize());
app.use(passport.session());

//app.use(app.router);

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

// bootstrap models
var models = require('./models');

// bootstrap routes
require("./routes")(app);

// error handler
app.use(function (err, req, res, next) {
  if (process.env.NODE_ENV != 'production') {
    if (typeof (err) == 'string') {
      res.send(Common.errorHandle(500, err));
      return;
    }
    throw err
  } else {
    if (typeof (err) == 'string') {
      res.send(Common.errorHandle(500, err));
      return;
    }
    res.send(Common.errorHandle(500, err.message));
  }
});

app.use('/', function (req, res, next) {
  res.redirect('/error-404.html');
});

// if (process.env.NODE_ENV == 'production') {
//   app.use(pmx.expressErrorHandler());
// }

// var options = {
//     key: fs.readFileSync('../cert/private.key'),
//     ca: [fs.readFileSync('../cert/CACertificate-1.cer'),
//          fs.readFileSync('../cert/CACertificate-2.cer')],
//     cert: fs.readFileSync('../cert/ServerCertificate.cer')
// };

if (process.env.NODE_ENV == 'production') {
  //https.createServer(options, app).listen(app.get('port'), function(){
  http.createServer(app).listen(app.get('port'), function(){
    logger.info('Express server listening on port ' + app.get('port'));
  });
} else {
  http.createServer(app).listen(app.get('port'), function(){
    logger.info('Express server listening on port ' + app.get('port'));
  });
}
